<template>
  <div class="app-container">
    <!-- <Svga :width="60" :height="60"></Svga> -->
    <el-form :model="param" :inline="true" label-width="68px">
      <el-row>
        <el-col :span="21">
          <el-form-item style="width:200px">
            <div>编号</div>
            <el-input v-model="param.releaseNo" clearable placeholder="请输入编号" />
          </el-form-item>
          <el-form-item style="width:400px"> 
            <InputBox :title="'提/还箱城市'" :inputVal1="param.boxStartCity" :inputVal2="param.boxBackCity" :inputBoxConfig="inputBoxConfig"  @inputChange="inputChange"></InputBox>
          </el-form-item>
          <el-form-item style="width:360px">
            <div>创建日期</div>
            <el-date-picker v-model="param.createDate" type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item style="width: 100%; position: absolute;bottom: 0">
            <el-button :icon="Refresh" @click="handleReSet">重置</el-button>
            <el-button :icon="Search" type="primary" @click="getTableData">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div style="margin-top: 10px;">
      <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange"
        style="float: left;"></cz-tages>
      <span style="margin-top: -40px;float: right;">
        <el-button :icon="Upload" type="primary" size="small" round @click="boxPublish($event, 'pitch')"
          plain>批量上架</el-button>
        <el-button :icon="Download" type="info" size="small" round @click="boxDown($event, 'pitch')"
          plain>批量下架</el-button>
        <el-button :icon="Delete" type="danger" size="small" round @click="isDelete($event, 'pitch')"
          plain>批量删除</el-button>
        <el-button :icon="Promotion" type="success" size="small" round
          @click="$router.push({ path: 'publish', query: { row: JSON.stringify({ 'isAdd': true }) } })"
          plain>发布</el-button>
      </span>

      <Table ref="tableRef" v-bind="table" @pageChange="onTablePageChange" :disableHeaderCheckbox="false" @activEdit="activEdit"
        @boxPublish="boxPublish" @showInfo="showInfo" @boxDown="boxDown" @isDelete="isDelete">
      </Table>
    </div>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" title="系统提示" width="500">
      <span>确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="activDelete">是的</el-button>
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
// import { getTable } from '@/api/boxRent'
// import { statusCount, publishPitch, downPitch, deletePitch } from '@/api/boxRent'
// import { getBoxEastSelfTable, statusCount, offShelf, onShelf, deletePitch } from '@/api/boxCallBack'
import {getTable,statusCount, publishPitch, downPitch, deletePitch } from '@/api/boxRent/indexNew.ts'

import citySelect from '@/components/citySelect'
// import Svga from '@/views/components/Svga'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import {
  Plus,
  Delete,
  Promotion,
  Edit,
  Message,
  Download,
  Upload
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import InputBox from '@/components/inputBox'
const param = reactive({
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '出租中', 10: '仓库中', 15: '待发布' },
  stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  typeList: []
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'releaseNo', key2: 'oidContainerNo', key3: 'containerClassify', colWidth: '150', title: '编号', type: '<change>', command: 'showInfo', isCheck: true },
    { key: 'id', colWidth: '420', title: '提箱/还箱城市', type: 'cityNew', isCheck: true },
    { key: 'boxUsagePeriod', colWidth: '120', title: '箱使期', type: 'add', after: '天', isCheck: true },
    { key: 'status', colWidth: '120', title: '发布状态', type: 'filter', filter: param.stateFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'createTime', colWidth: '300', title: '创建日期', sortable: true, type: 'date',timeDuration:4, isCheck: true },
    {
      key: 'operate',
      colWidth: '200',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // content: '编辑',
          // icon: 'Edit',
          name: '编辑',
          command: 'activEdit',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '下架',
          // icon: 'Download',
          name: '下架',
          command: 'boxDown',
          isShow: (row: { status: string; }) => {
            return row.status == '5';
          },
        },
        {
          // content: '上架',
          // icon: 'Upload',
          name: '上架',
          command: 'boxPublish',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '删除',
          // icon: 'Delete',
          name: '删除',
          command: 'isDelete',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

//修改提还箱城市
const inputChange = (val1, val2) => {
  param.boxStartCity = Array.isArray(val1) ? val1.join(',') : val1; // 提箱城市
  param.boxBackCity = Array.isArray(val2) ? val2.join(',') : val2; // 还箱城市
}

function handleTypeChange(val: any) {
  // console.log(val)
  param.status = val
  getTableData()
}

//初始化
function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    carryCityId: param.boxStartCity,
    returnCityId: param.boxBackCity,
    status: param.status - 0 || null,
    releaseNo:param.releaseNo?.trim()|| ""
  };
  if (param.createDate) {
    data.beginCreateTime = param.createDate[0];
    data.endCreateTime = param.createDate[1];
  }
  table.config.loading = true;
  //列表
  getTable(data).then((res: any) => {
    // console.log(JSON.parse(JSON.stringify(res.data.list)))
    console.log("res111",res)
    table.data = JSON.parse(JSON.stringify(res.data.list));
    table.data.forEach((item: any) => {
      let mainFileList = JSON.parse(item.mainFileList);
      item.imgUrl = mainFileList.map((item: any) => {
        return item.url
      })[0];
    });
    table.config.total = res.data.total;
  });
  //汇总
  data.rentSource = 5 // 租箱来源: 5 - 集装箱公司发布 10 - 货代发布
  statusCount(data).then((res: { data: any }) => {
    let total = 0;
    const resList = res.data // [ { status: 5, totalQty: 0 },{ status: 10, totalQty: 0 },{ status: 15, totalQty: 0 } ]
    const list = [
      { id: 0, name: '全部', num: 0 },
      { id: 5, name: '出租中', num: 0 },
      { id: 10, name: '仓库中', num: 0 },
      { id: 15, name: '待发布', num: 0 }
    ]
    list.forEach(item => {
      resList.forEach((obj: { status: number; totalQty: number }) => {
        if (item.id == obj.status) {
          item.num = obj.totalQty
          total += obj.totalQty
        }
      })
    })
    list.map(obj => {
      if (obj.id == 0) {
        obj.num = total
      }
    })
    param.typeList = list
  });
  table.config.loading = false;
}
//重置
function handleReSet() {
  param.releaseNo = null
  param.boxStartCity = null
  param.boxBackCity = null
  param.createDate = []
  param.cityList = []
  getTableData()
}

const inputBoxConfig = reactive({
  placeholder1:"请输入提箱城市",
  placeholder2:"请输入还箱城市",
  multiple:true
})

//编辑
const router = useRouter();
const activEdit = (row: { id: any }) => {
  router.push({
    path: 'publish',
    query: {
      type:1,
      // secondaryEditing: "true", // 是否是下架中编辑
      id: JSON.stringify(row.id)
    }
  })
};
//详情
const showInfo = (row: { id: any }) => {
  // row.isInfo=true
  router.push({
    path: 'publish',
    query: {
      type:2,
      // secondaryEditing: "true", // 是否是下架中编辑
      id: JSON.stringify(row.id),
    }
  })
};
//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
const boxPublish = (row: { id: any }, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要上架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  publishPitch(ids).then(() => {
    getTableData()
  })
};
const boxDown = (row: any, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要下架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  downPitch(ids).then((res: any) => {
    getTableData()
  })
};

//删除 
let deleteList = ref([])
const isDelete = (row: any, opr: any) => {
  if (opr == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要删除的订单')
    }
    deleteList.value = selection.value
  } else {
    deleteList.value = [row.id]
  }
  param.dialogVisible = true;
};
const activDelete = () => {
  let ids = [...deleteList.value]
  deletePitch(ids).then((res: any) => {
    getTableData()
  })
  param.dialogVisible = false;
};


//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};


onActivated(() => {
  getTableData()
})

</script>
<style scoped>

.input-wrapper >>> .el-input__wrapper {
  border: none !important;
  box-shadow: none !important;
  height: 28px;
}
</style>